import { Select, Spin } from 'antd';
import debounce from 'lodash/debounce';
import _ from 'lodash';
import { connect } from 'dva';
const Option = Select.Option;

@connect(({ userSelect, loading }) => ({
  searchUsers: userSelect.searchUsers,
  loading: loading.models.testcenter_user_select
}))
export default class UserSelect extends React.Component {

  state = {
    value: []
  }

  convertUsersToSelectValues = (users) => {
    let key_values = [];
    if (users || _.isArray(users)) {
      key_values = users.map((user) => {
        return {
          key: `${user.id}`,
          label: `${user.realName} ${user.userName}`
        }
      })
    }
    return key_values;
  }

  componentDidMount() {
    this.fetchUser = debounce(this.fetchUser, 800);
    this.roleId = this.props.roleId;
    if ([1, 2, 3].indexOf(this.roleId) < 0) {
      return;
    }
    let users = this.props.users;
    let key_values = this.convertUsersToSelectValues(users);
    this.setState({
      value: key_values
    });
    this.triggerChange(key_values);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.disabled) {
      if (nextProps.users !== this.props.users) {
        let users = nextProps.users;
        let key_values = this.convertUsersToSelectValues(users);
        this.setState({
          value: key_values
        });
      }
    }
  }

  fetchUser = (value) => {
    this.props.dispatch({
      type: 'userSelect/search',
      payload: { roleId: this.roleId, userName: value }
    })
  }

  handleFocus = () => {
    this.props.dispatch({
      type: 'userSelect/search',
      payload: { roleId: this.roleId }
    })
  }

  handleChange = (value) => {
    this.setState({
      value: _.uniqBy(value, 'key')
    });
    this.triggerChange(value);
  }

  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    const componentDidMount = this.componentDidMount;
    let values = [];
    if (!_.isUndefined(changedValue)) {
      changedValue = changedValue.map((cv) => {
        values.push({
          id: _.toInteger(cv.key)
        })
      });
    }
    if (onChange || componentDidMount) {
      onChange(Object.assign(values));
    }
  }

  handleDisSelect = (value) => {
    let users = _.remove(this.state.value, (user) => {
      return user.id !== _.toInteger(value.key)
    });
    this.setState({
      value: users
    });
  }

  handleSelect = (value) => {
    let users = _.uniqBy(this.state.value.concat(value), 'key');
    this.setState({
      value: users
    });
  }

  configOption = (users) => {
    let options = _.isEmpty(users) ? null :
      this.props.searchUsers.map(user => <Option key={user.id} >{`${user.realName} ${user.userName}`}</Option>)
    return options;
  }

  render() {
    let options = [];
    if(!this.props.disabled){
      let searchOutUsers = this.props.searchUsers;
      options = this.configOption(searchOutUsers);
    }
    

    return (
      <Select
        mode="multiple"
        labelInValue
        placeholder={this.props.holder}
        notFoundContent={ this.props.loading ? <Spin size="small" /> : null}
        filterOption={false}
        onSearch={this.fetchUser}
        onChange={this.handleChange}
        onFocus={this.handleFocus}
        onSelect={this.handleSelect}
        onDeselect={this.handleSelect}
        disabled={this.props.disabled}
        style={{ width: '100%' }}
        value={this.state.value}
      >
        {options}
      </Select>
    );
  }
}


